<?php

class PageController extends FrontEndController
{
	/**
	 * @var string the name of the GET parameter that contains the requested page name. Defaults to 'page'.
	 */
	public $pageParam='page';

	private $_pageName;
	private $_model;
	
	/**
	 * index action, displays the page desribed by the 'page' parameter
	 */
	public function actionIndex(){
		$this->loadModelByName($this->getRequestedPage());
		
		$this->renderPage();
	}
	
	/**
	 * Renders the page
	 * @throws CHttpException
	 */
	protected function renderPage(){
		$this->layout = $this->_model->layout->path;
		$this->pageTitle = $this->_model->title . $this->getPageTitlePostfix();
		
		if(count($this->_model->nodes) < 1)
			throw new CHttpException(500, 'Internal server error.');
		$this->render('index', array(
			'title'=>$this->_model->title,
			'content'=>$this->_model->nodes[0]->content,
		));
	}
	
	/**
	 * Loads the page model
	 * @param string $name
	 * @throws CHttpException
	 */
	public function loadModelByName($name){
		$this->_model=Page::model()->find('name=:name', array(':name' => $name));
		if($this->_model===null)
			throw new CHttpException(404,'The requested page "' . $name . '" does not exist.');
	}

	/**
	 * Returns the name of the node requested by the user.
	 * If the user doesn't specify any node, the $defaultNode will be returned.
	 * @return string the name of the node requested by the user.
	 */
	public function getRequestedPage(){
		if($this->_pageName===null)
		{
			if(!empty($_GET[$this->pageParam]))
				$this->_pageName=$_GET[$this->pageParam];
			else
				$this->_pageName=self::getIndexPageName();
		}
		return $this->_pageName;
	}
	
	/**
	 * Finds the index page
	 * @return string name of the index page
	 */
	public static function getIndexPageName(){
		return Page::model()->findByPk(Yii::app()->settings->get('page', 'indexPageId'))->name;
	}

	/**
	 * (non-PHPdoc)
	 * @see protected/components/FrontEndController::getMenu()
	 */
	public function getMenu($parentId=null, $depth=5){
		if($depth>0){
			$items=array();
			$model = $this->_model;
			
			$navigation = $model->navigation($parentId)->findAll();
			foreach($navigation as $item){
				$items[] = CMap::mergeArray(
					array(
						'label'=>$item->title,
						'url'=>array('/page/index', 'page'=>$item->name),
					), $this->getMenu($item->id, $depth-1));
			}
			$out = array('items'=>$items);
			
			return $out;
		} else {
			return array();
		}
	}
}
